<?php

namespace app\admin\service;

use app\admin\model\Abnormal;
use app\admin\model\Operation;
use app\admin\model\Street;
use app\admin\model\Uav;
use app\admin\model\User;

/**
 * 无人机
 */
class UavService
{
    /**
     * @var Operation
     */
    private $model;

    public function __construct()
    {
        $this->model = new Uav;
    }

    public function lists($all): array
    {
        $query = $this->model->where('mark', 1);

        $data = [
            'msg'       => 'success',
            'timestamp' => time(),
            'code'      => 0,
            'count'     => (clone $query)->count('id')
        ];
        if (!$all) {
            $query->page(PAGE, PERPAGE);
        }
        $data['data'] = $query->order('id', 'desc')->select()->toArray();
        if ($all) {
            $token = $this->getToken();
            foreach ($data['data'] as &$val) {
                $val['ws'] = 'ws://118.31.13.222:10009/api/uavHandler?token=' . $token . '&equipType=2&equipId=' . $val['airport_id'];
            }
        }
        return $data;
    }

    public function info($id)
    {
        return $this->model->where('plane_id', $id)->find();
    }

    public function save($param, $userId)
    {
        $saveData = [$param];
        if (!empty($param['id'])) {
            $saveData[]           = ['id' => $param['id']];
            $param['update_user'] = $userId;
        } else {
            $param['create_user'] = $userId;
        }
        $this->model->allowField(true)->save(...$saveData);
    }

    public function delete($id)
    {
        $this->model->where('id', $id)->update(['mark' => 0]);
    }

    private function getToken()
    {
        $url = 'http://118.31.13.222:9022/user/token?accessKey=7A57A5A743894A0E&secret=21dab17afb987530111f64f123597f1c';

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 300);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        $response = curl_exec($curl);
        curl_close($curl);
        $response = json_decode($response, true);

        return $response['data'];
    }
}
